package com.yequan.work;

import org.apache.commons.codec.binary.*;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;

/**
 * @author yequan
 * @date 2021/03/02 11:28
 **/
public class EncryptUtil {

    // MD5的引入
    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++){
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    private static byte[] iv = { (byte) 0x16, (byte) 0x83, (byte) 0x0A,
            (byte) 0x8D, (byte) 0x27, (byte) 0x25, (byte) 0x43, (byte) 0xBE };

    /**
     * 加密
     * @param encryptString
     * @return
     */
    public static String encryptDES(String encryptString) {
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(iv, "DES");
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

            return bytesToHexString(encryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 加密
     * @param encryptString
     * @param encryptKey
     * @return
     */
    public static String encryptDES(String encryptString, String encryptKey) {
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(encryptKey.substring(
                    0, 8).getBytes());
            SecretKeySpec key = new SecretKeySpec(encryptKey.substring(0, 8)
                    .getBytes(), "DES");
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

            return bytesToHexString(encryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 解密
     * @param decryptString
     * @return
     */
    public static String decryptDES(String decryptString) {
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(iv, "DES");
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte decryptedData[] = cipher.doFinal(hexStringToBytes(decryptString));
            return new String(decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 解密
     * @param decryptString
     * @param decryptKey
     * @return
     * @throws Exception
     */
    public static String decryptDES(String decryptString, String decryptKey)
            throws Exception {
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(hexStringToBytes(decryptString));

        return new String(decryptedData);
    }

    public static String bytesToHexString(byte[] bs) {
        StringBuffer sb = new StringBuffer();
        String hex = "";
        for (int i = 0; i < bs.length; i++) {
            hex = Integer.toHexString(bs[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }

    public static byte[] hexStringToBytes(String in) {
        byte[] arrB = in.getBytes();
        int iLen = arrB.length;
        // 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
        byte[] arrOut = new byte[iLen / 2];
        for (int i = 0; i < iLen; i = i + 2) {
            String strTmp = new String(arrB, i, 2);
            arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
        }
        return arrOut;
    }

    public static String encryptDESBase64(String encryptString, String encryptKey) {
        try{
            IvParameterSpec zeroIv = new IvParameterSpec(encryptKey.substring(0, 8).getBytes());
            SecretKeySpec key = new SecretKeySpec(encryptKey.substring(0, 8).getBytes(), "DES");
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

            return Base64.encodeBase64String(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptDESBase64(String decryptString, String decryptKey) throws Exception {
        if (StringUtils.isBlank(decryptString)) {
            return decryptString;
        }
        // 这里不应该做 decryptString.trim() 操作，如果加密后 +在首位或者末尾，后台接受变为 " "就会在两端。会出现真数据误以为假数据去处理
        //解决 Get 或者 Delete 请求，base64 加密后出现 + 号，而后台接受转为空格的情况 。
        String subStr = " ";
        String replaceStr = "+";
        if (decryptString.contains(subStr)) {
            decryptString = decryptString.replaceAll(subStr, replaceStr);
        }
        byte[] byteMi = Base64.decodeBase64(decryptString);
        IvParameterSpec zeroIv = new IvParameterSpec(decryptKey.substring(0, 8).getBytes());
        SecretKeySpec key = new SecretKeySpec(decryptKey.substring(0, 8).getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);
        return new String(decryptedData);
    }

    public static void main(String[] args) throws Exception {
//        String decryptDdcInfo = EncryptUtil.decryptDESBase64("ehAq+CFEfF2z2cAMy7BtBxv6MmN6Lnw49+G4bQtNoRGBx1r3T/WMW3CWOuetLfBNMwemNYVrCEBDybFjZqKb17jkmMydFNgLNqPL+4irGxM5PCAG8/+WFQE3gqasswt/I3pPU0ZBAyAOoDvSgKMk5LwF/qtHe3ise0ypRM7pwVIIBLcWviEDHOMFDZhaTDI/YoNd7VRz/iGyfy5duhlTfXfKgEDsKzCxfoBB20zuef1+mtztJ3ZE4CDKivGbUS8RAERTrS5ic0qVrBBDd8nY4SMRqpb38ZdL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bShORr6y6EQ=");
//        String decryptDdcInfo = EncryptUtil.decryptDESBase64("ehAq+CFEfF3NUPuHmnLV64npIbfbiRMZgOSmDu811aBkZX2yeZD7emz3G52uMaziQJkYIgwG+wFjWeLueQPJx7JQj6myB4mWFX6BFOftCEY3qvpKWkLNu/te3zgywgqquZoQxUk3916I0Bj1EYyhG5MB8EVyll1LkjXhtF6/quGLRxw6QjOxP3UzWcDZlfFwMJSH6MNL/7U2D+ERm7JWnku3hyBZylp6SurCZZjlvwhhgclWp9BdJ2a3nqAaUtu3PIpp8RMB4du87Po9sJ5gyabemIwuhJl9t6IfSpVCK3KI03msaTR13NwHZFDR+axz+cLM4M68O6hAOzIUmH1jRRl58ajb0MBfvI2Xu9vMit1Zy6CzxtS0YAk3+UFZFcOXeyPjsrQTfCWz4npmD0v43jd+XhVMYlYIBMsZyu0JwikxAO8hyyZAuylDuJ8NW8ebgipRwIT2DxbgamNDArLTEqI6y3F/LvTphtxs5BEESY4ft7NvnzAwti3y4D3uSR3WyLDbeyW3yAKrFmsSx7GQvxrsK4KCT3cW7aYbUhp8gy1ois7QxuCYVehDLkORwheCxn415s9CW+mykVIGzLLiCqHfDJyR5kIquDLQhA/XaetbhO0vEyC6A+RvHOTYpkLp7BgWERwmR8uoQoa03O4NXSfFBDYio5K3IzNqqaWkmrn37F5kCDGo9ff74LKG3de9wIzDPiKwBCx5caALdIwb8uihqxu+Enyh5okV1JzFZx+1BMuNyu+U8ZoIuK0IZ6ie2/rPRZ0EQ9xIpKG3VL3irwmAlUVcoMjmRzHFvzLledOkgixPwv+sj3EO95i+IcmOVhXOaeZSd147Sxx7kJZODBAlutHnfvQ9GEjnUk68973qQaqD5cCP6huhsSXVG+tafkzoG5kOpNYC0jq4pnQkiQ92c60xO9W4xVYyL24yKGL9B4eIHW90L9qasKXjALH7cIUtPf6irQRMsEQswtIDYCfiE5BqI1+2nWOr9c/lLucHHNsUYlw9x56J4JY5lfGw8BSFImPfnH6RkRt6ufyRk3WxiZu1aG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BR33nF/wId8DbACz6r+YgM2eFZsuQ9+9GxeauP7Al0s2utxjJSdO2VxUTpO3Nn8JBa4MzjLcNzK5dCe9BtFs3A742xdRpq0mlh0PpWHpWSUrKfI4e+jD4Y7GFyEylg1KqS4DZLl7XzX7574TpSfIYZnc+Qtbf4zpnbhNdz9O5r+pQLBKUkNn5f1GN8r0=", "bShORr6y6EQ=");

       String ddc= "ddcinfo:{\"mobiletype\":\"1\",\"env_info\":\"{\\\"env\\\":\\\"ONLINE\\\",\\\"bapi\\\":\\\"http:\\/\\/bapi-clb.didapinche.com\\/\\\",\\\"im\\\":\\\"im-1.didapinche.com:7400\\\",\\\"restful\\\":\\\"https:\\/\\/capis-3.didapinche.com\\/\\\",\\\"h5\\\":\\\"https:\\/\\/www.didapinche.com\\/\\\",\\\"config_name\\\":\\\"pm_yqNotify_pm_versionSettings_ui_car_corlor_guangdong_time_inter_test\\\",\\\"config_sign\\\":\\\"1644996859\\\"}\",\"dir\":-1,\"lip\":\"10.10.10.95\",\"speed\":-1,\"deviceToken\":\"00268e1c747e18dd126d24a40240110c97e8699b0d700f8315988d59d3fe7120\",\"latitude\":\"40.024800\",\"location_time\":\"20220228095819\",\"version\":\"8.24.0\",\"os\":\"iOS_14.3;v8.24.0\",\"udid\":\"\",\"altitude\":39.410521030426025,\"net\":\"wifi\",\"identifier\":\"com.didapinche.taxi\",\"longitude\":\"116.474820\",\"model\":\"iPhone11,2\",\"role\":\"2\",\"ap_mac\":\"\",\"screen\":\"375*812\",\"idfa\":\"C300A45B-40B3-4E34-A8CE-203A69CB328B\"}";

        System.out.println(decryptDdcInfo);
    }

}
